package org.nmgyjt.springboot.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nimbusds.jose.JOSEException;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.CsBusiness;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.CsSystemSourceType;
import org.nmgyjt.springboot.entity.area.Area;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/cs/org")
@CrossOrigin
public class CsSystemOrgController {

    @Autowired
    private ICsSystemDeptService service;

    @Autowired
    private ICsSystemAdminService adminService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private ICsSystemSourceTypeService sourceTypeService;

    @Autowired
    private ICsSystemSourcePreSetInfoService preSetInfoService;

    @Autowired
    PropertiesUtil propertiesUtil;

    @Autowired
    private ICsBusinessService csBusinessService;

    @PostMapping("/list")
    public ApiRes getOrgList(@RequestBody CsSystemOrgSelectBean bean) throws Exception {

        return ApiRes.ok(service.selectOrgList(bean));
    }

    @PostMapping("/list/detail")
    public ApiRes getOrgDetailList(@RequestBody CsSystemOrgSelectBean bean) throws ParseException, JOSEException {

        CsSystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getPhone()).eq(CsSystemAdmin::getOrgId, bean.getOrgId()).orderByDesc(CsSystemAdmin::getId).last("limit 1"));
        return ApiRes.ok(admin);
    }

    @PostMapping("/detail")
    public ApiRes detail(@RequestBody @Validated CsSystemIDSelectBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(service.detailCsSystemOrg(bean));
    }
    @PostMapping("/pre-detail")
    public ApiRes presetDetail(@RequestBody @Validated CsSystemOrgSelectBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(service.selectOrgResetDetail(bean));
    }

    @PostMapping("/beyong")
    public ApiRes detail(@RequestBody @Validated CsSystemBeyongDeptSelectBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(service.detailCsSystemBeyongOrg(bean));
    }

    @PostMapping("/init")
    public ApiRes initCreateOrg(@RequestBody @Validated CsSystemIDSelectBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(service.initOrg(bean));
    }

    @PostMapping("/init_org")
    public ApiRes initeOrg(@RequestBody @Validated CsSystemIDSelectBean bean) throws ParseException, JOSEException {
        service.initInstitution(bean);
        return ApiRes.ok();
    }

    @PostMapping("/init_delete")
    public ApiRes initDeleteOrg(@RequestBody @Validated CsSystemOrgInitDeleteBean bean) throws ParseException, JOSEException {
        service.initDeleteOrg(bean);
        return ApiRes.ok();
    }


    @PostMapping("/new")
    public ApiRes createOrg(@RequestBody @Validated CsSystemOrgCreateBean bean) throws ParseException, JOSEException {
        service.createCsSystemOrg(bean);
        return ApiRes.ok();
    }

    @PostMapping("/update")
    public ApiRes updateOrg(@RequestBody @Validated CsSystemOrgCreateBean bean) throws ParseException, JOSEException {
        service.createCsSystemOrg(bean);
        return ApiRes.ok();
    }

    @PostMapping("/source/mount")
    public ApiRes statisticSourcePreSetMount(@RequestBody @Validated CsSystemStatisticSourcePreSetMountBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(preSetInfoService.statisticSourcePreSetInfos(bean));
    }

    @PostMapping("/source/list")
    public ApiRes selectSourcePreSetList(@RequestBody @Validated CsSystemStatisticSourcePreSetMountBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(preSetInfoService.selectSourcePreSetInfos(bean));
    }

    @PostMapping("/source/update")
    public ApiRes selectSourcePreSetList(@RequestBody @Validated CsSystemSourcePreSetUpdateBean bean) throws ParseException, JOSEException {
        return ApiRes.ok(preSetInfoService.updateSourcePreSetInfos(bean));
    }

    @PostMapping("/rescue/duty")
    public ApiRes getRescueTeamDuties() throws ParseException, JOSEException {

        String content = propertiesUtil.propLoad("spring.nmgyjt.rescue.team.duty");
        if (StringUtils.isNotEmpty(content)) {

            String[] strings = content.split(",");
            List<String> typeList = Arrays.asList(strings);
            return ApiRes.ok(typeList);
        } else {

            return ApiRes.ok(new ArrayList<>());
        }
    }


    @PostMapping("/level")
    public ApiRes selectTeamLevel(@RequestBody CsSystemParIDSelectBean bean) throws ParseException, JOSEException {
        if (null == bean || StringUtils.isEmpty(bean.getParId())) {
            return ApiRes.fail(400, "获取机构列表的参数不允许为空");
        }


        Area are = areaService.getById(bean.getParId());
        if (null == are) {
            return ApiRes.fail(400, "获取机构列表的参数不正确,获取救援队伍列表失败");
        }

        return ApiRes.ok(service.selectTeamLevel(are));
    }



    @PostMapping("/type")
    public ApiRes selectSourceType(@RequestBody CsSystemParIDSelectBean bean) throws ParseException, JOSEException {
        if (null == bean || StringUtils.isEmpty(bean.getParId())) {
            return ApiRes.fail(400, "获取资源类型的参数不允许为空");
        }
        if ("1000002024".equals(bean.getParId())){
            List<CsSystemSourceType> list = new ArrayList<>();
            List<CsBusiness>  cab1List =
                    csBusinessService.list(new LambdaQueryWrapper<CsBusiness>().eq(CsBusiness::getParentId, "0")
                            .orderByAsc(CsBusiness::getUdOrder));
            for (CsBusiness cab1 : cab1List){
                CsSystemSourceType css1 = new CsSystemSourceType();
                css1.setId(cab1.getBusinessId());
                css1.setParentId(cab1.getParentId());
                css1.setName(cab1.getName());
                List<CsBusiness>  cab2List =
                        csBusinessService.list(new LambdaQueryWrapper<CsBusiness>().eq(CsBusiness::getParentId, cab1.getBusinessId())
                                .orderByAsc(CsBusiness::getUdOrder));
                List<CsSystemSourceType> children = new ArrayList<>();
                for (CsBusiness cab2 : cab2List) {
                    CsSystemSourceType css2 = new CsSystemSourceType();
                    css2.setId(cab2.getBusinessId());
                    css2.setParentId(cab2.getParentId());
                    css2.setName(cab2.getName());
                    children.add(css2);
                }
                css1.setChildren(children);
                list.add(css1);
            }
            return ApiRes.ok(list);
        }

        List<CsSystemSourceType> list = sourceTypeService.list(new LambdaQueryWrapper<CsSystemSourceType>().eq(CsSystemSourceType::getParentId, bean.getParId())
                .eq(CsSystemSourceType::getStatus,"ENABLED"));
        if (!CollectionUtils.isEmpty(list) && bean.getParId().contains("1000000")) {
            list = sourceTypeService.list(new LambdaQueryWrapper<CsSystemSourceType>().eq(CsSystemSourceType::getParentId, list.get(0).getId()).eq(CsSystemSourceType::getStatus,"ENABLED"));

        }
        if (!CollectionUtils.isEmpty(list) && list.size() > 0) {
            for (CsSystemSourceType type : list) {
                List<CsSystemSourceType> types = sourceTypeService.list(new LambdaQueryWrapper<CsSystemSourceType>().eq(CsSystemSourceType::getParentId, type.getId()).eq(CsSystemSourceType::getStatus,"ENABLED"));
                if (null != types && !CollectionUtils.isEmpty(types)) {
                    type.setChildren(types);
                }
            }
        }
        return ApiRes.ok(list);
    }

    @PostMapping("/ud")
    public ApiRes udOrder(@RequestBody @Validated List<CsSystemUdOrderBean> beans) throws ParseException, JOSEException {
        service.udOrderCsSystemOrg(beans);
        return ApiRes.ok();
    }

    @PostMapping("/delete")
    public ApiRes deleteOrg(@RequestBody @Validated CsSystemOrgDeleteBean bean) throws
            ParseException, JOSEException {
       /* CsSystemAdmin admin = adminService.getById(bean.getId());
        if (StringUtils.isNotEmpty(bean.getId()) && null == admin) {
            return ApiRes.fail(401, "管理员无权删除部门,删除失败");
        }
*/
        String str = service.deleteCsSystemOrg(bean);
        if (StringUtils.isNotEmpty(str)) {
            return ApiRes.fail(501, str);
        }
        return ApiRes.ok();
    }

}
